﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Emz.Core.DataAccess;
using System.Data.Entity;
using Emz.Core.Helpers;
using System.Data;
using System.Linq.Expressions;

namespace Emz.Core.Base
{
    public abstract class RepositoryBase<T> where T : class
    {
        //private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        private DbContext _dataContext;
        private readonly IDbSet<T> _dbset;
        protected RepositoryBase(DbContext dataContext)
        {
            _dataContext = dataContext;
            _dbset = _dataContext.Set<T>();
        }

        private DbContext DbContext
        {
            get { return _dataContext; }
            set
            {
                _dataContext = value;        
            }
        }

        

        public virtual void Add(T entity)
        {
            _dbset.Add(entity);
        }
        public virtual void Update(T entity)
        {
            _dbset.Attach(entity);
            _dataContext.Entry(entity).State = EntityState.Modified;
        }
        public virtual void Delete(T entity)
        {
            _dbset.Remove(entity);
        }
        public virtual void Delete(Expression<Func<T, bool>> where)
        {
            IEnumerable<T> objects = _dbset.Where<T>(where).AsEnumerable();
            foreach (T obj in objects)
                _dbset.Remove(obj);
        }
        public virtual T GetById(long id)
        {
            return _dbset.Find(id);
        }
        public virtual T GetById(string id)
        {
            return _dbset.Find(id);
        }


        public IQueryable<T> GetQuery()
        {
            return _dbset;
        }
        public virtual IEnumerable<T> GetAll()
        {
            return _dbset.ToList();
        }
        public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
        {
            return _dbset.Where(where).ToList();
        }
        public T Get(Expression<Func<T, bool>> where)
        {
            return _dbset.Where(where).FirstOrDefault<T>();
        }
        
        public void Save(out string message)
        {
            try
            {
                DbContext.SaveChanges();
                message = "Saved";
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
        }
    }
}
